import React, { Component } from "react";
import {
  Button,
  DatePicker,
  Input,
  Table,
  Divider,
  Popconfirm,
  Badge,
  message
  // Popover,
} from "antd";
import { connect } from "dva";
import moment from "moment";
import { Link } from "dva/router";
import tableFilter from "../../../components/tableFilter";
import styles from "./PlanManage.less";
import PushModal from "./PushModal";

const { RangePicker } = DatePicker;
const { Search } = Input;

@connect(stores => ({
  userData: stores.user,
  planData: stores.planlist,
  addPlanData: stores.addPlan,
  orgData: stores.adddataSource,
  EditplanData: stores.addPlan
}))
@tableFilter
class PlanManage extends Component {
  state = {
    pageNum: 1,
    pageSize: 10,
    ownerDept: [],
    planState: [],
    startTime: "",
    endTime: "",
    inputContent: "",
    orderByClause: "time_create",
    ascOrDesc: "desc",
    visible: false,
    pushChannel: []
  };

  componentDidMount() {
    this.origiSend();
    const { dispatch } = this.props;
    dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });
  }

  origiSend = () => {
    const { dispatch } = this.props;
    const { pageNum, pageSize, orderByClause, ascOrDesc } = this.state;
    dispatch({
      type: "planlist/planList",
      payload: {
        pageNum,
        pageSize,
        orderByClause,
        ascOrDesc
      }
    });
    dispatch({ type: "addPlan/getPushChannel", payload: {} });
    dispatch({ type: "planlist/getDepart", payload: {} });
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { ownerDept, planState, pushChannel } = this.state;
    this.setState(
      {
        pageNum:
          (filters.ownerDeptName && filters.ownerDeptName !== ownerDept) ||
          (filters.auditStatus && filters.auditStatus !== planState) ||
          (filters.channelName && filters.channelName !== pushChannel)
            ? 1
            : current,
        pageSize,
        ascOrDesc: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        ownerDept: filters.ownerDeptName ? filters.ownerDeptName : [],
        planState: filters.auditStatus ? filters.auditStatus : [],
        pushChannel: filters.channelName ? filters.channelName : []
      },
      () => {
        this.filterFun();
      }
    );
  };

  dateChange = e => {
    if (e && e.length > 0) {
      this.setState(
        {
          startTime: e[0].format("YYYY-MM-DD"),
          endTime: e[1].format("YYYY-MM-DD"),
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          startTime: "",
          endTime: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleSearch = e => {
    // const { dispatch } = this.props;
    this.setState(
      {
        inputContent: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const {
      ownerDept,
      planState,
      orderByClause,
      pageSize,
      ascOrDesc,
      pageNum,
      startTime,
      endTime,
      pushChannel,
      inputContent
    } = this.state;
    const { dispatch } = this.props;
    const temp = {
      ascOrDesc,
      ownerDept: ownerDept[0],
      auditStatus: planState[0],
      pushChannelId: pushChannel[0],
      orderByClause,
      creTimeStart: startTime,
      creTimeEnd: endTime,
      name: inputContent === "" ? undefined : inputContent
    };
    dispatch({
      type: "planlist/planList",
      payload: {
        pageNum: String(pageNum),
        pageSize: String(pageSize),
        ...temp
      }
    });
    dispatch({ type: "addPlan/getPushChannel", payload: { ...temp } });
    dispatch({ type: "planlist/getDepart", payload: { ...temp } });
  };

  startconfirm = planId => {
    const { dispatch } = this.props;
    dispatch({
      type: "planlist/putOnline",
      payload: { planId }
    }).then(() => {
      const { onLineErr } = this.props.planData;
      if (onLineErr === 0) {
        message.success("发布成功");
        this.origiSend();
      } else {
        message.error("发布失败");
      }
    });
  };

  endconfirm = planId => {
    const { dispatch } = this.props;
    dispatch({
      type: "planlist/putOffLine",
      payload: { planId }
    }).then(() => {
      const { offLineErr } = this.props.planData;
      if (offLineErr === 0) {
        message.success("下线成功");
        this.origiSend();
      } else {
        message.error("下线失败");
      }
    });
  };

  deleteconfirm = planId => {
    const { dispatch } = this.props;
    dispatch({
      type: "planlist/delPlan",
      payload: { planId }
    }).then((res = {}) => {
      if (res.errCode === 0) {
        message.success("删除成功");
        this.origiSend();
      } else {
        message.error("删除失败");
      }
    });
  };

  pushModal = () => {
    const { visible } = this.state;
    this.setState({
      visible: !visible
    });
  };

  handleOk = () => {
    this.setState({
      visible: false
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  renderTip = () => (
    /*     if (text === 1) {
      return (
        <div>
          <Badge status="success" />
          <Popover content={this.renderTip()} title="">
            <span>已发布</span>
          </Popover>
        </div>
      );
    } */
    <div>
      <p><span>分局管理员：</span><Badge status="success" />审批通过</p>
      <p><span>市局管理员：</span><Badge status="success" />审批通过</p>
    </div>
  );

  renderState = text => {
    if (text === 1) {
      return <Badge status="success" text="已发布" />;
    }
    if (text === -1) {
      return <Badge status="error" text="未通过" />;
    }
    if (text === 2) {
      return <Badge status="default" text="未发布" />;
    }
    return <Badge status="warning" text="待审批" />;
  };

  clearChange = e => {
    if (e.target.value === "") {
      this.setState(
        {
          inputContent: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  render() {
    const {
      planData,
      EditplanData,
      dispatch,
      userData: { btnAuthority = [] } = {},
      getColumnSearchProps = () => {}
    } = this.props;
    const { pageNum } = this.state;
    const { planList = [], loading, totalCount, departList = [] } = planData;
    const newList = departList.map(item => {
      const tmp = { text: item.ownerDeptName, value: item.ownerDept };
      return tmp;
    });
    const { channelList = [] } = EditplanData;
    const listChannel = [];
    channelList.forEach(item => {
      listChannel.push({ value: item.pushChannelId, text: item.description });
    });
    const columns = [
      {
        title: "计划名称",
        dataIndex: "planName",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "推送场景",
        dataIndex: "templateName",
        render: text => <span title={text}>{text}</span>
      },
      {
        title: "推送渠道",
        dataIndex: "channelName",
        filters: listChannel,
        filterMultiple: false
      },
      {
        title: "归属部门",
        dataIndex: "ownerDeptName",
        filters: newList,
        filterMultiple: false,
        ...getColumnSearchProps(newList)
      },
      {
        title: "状态",
        dataIndex: "auditStatus",
        filters: [
          { text: "待审批", value: 0 },
          { text: "已发布", value: 1 },
          { text: "未通过", value: -1 },
          { text: "未发布", value: 2 }
        ],
        filterMultiple: false,
        render: text => this.renderState(text)
      },
      {
        title: "管理员",
        dataIndex: "owner",
        render: (text, record) =>
          JSON.parse(record.owner) && JSON.parse(record.owner).length > 0
            ? JSON.parse(record.owner)[0].name
            : "-"
      },
      {
        title: "创建时间",
        dataIndex: "timeCreate",
        sorter: true,
        defaultSortOrder: "descend",
        render: (text, record) =>
          moment(record.timeCreate).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: "操作",
        dataIndex: "operate",
        fixed: "right",
        width: 140,
        render: (text, record) => {
          const states = { operate: "mod", planId: record.planId };
          return (
            <span>
              <Link
                to={`/intellPush/recommendCenter/plan/planDetail?key=${JSON.stringify(
                  { operate: "detail", planId: record.planId }
                )}`}
              >
                详情
              </Link>

              <Divider type="vertical" />

              <Link
                to={`/intellPush/recommendCenter/plan/editPlan?key=${JSON.stringify(
                  states
                )}`}
                disabled={
                  record.auditStatus === 0 ||
                  record.auditStatus === 1 ||
                  !record.dataPrivilege
                }
              >
                编辑
              </Link>

              <Divider type="vertical" />
              {record.auditStatus === 2 || record.auditStatus === -1 ? (
                <Popconfirm
                  title="你是否要申请发布此计划?"
                  onConfirm={() => this.startconfirm(record.planId)}
                  onCancel={this.startcancel}
                  okText="确定"
                  cancelText="取消"
                  placement="topRight"
                >
                  <a disabled={!record.dataPrivilege}>发布</a>
                </Popconfirm>
              ) : (
                <Popconfirm
                  title="你是否要下线此计划?"
                  onConfirm={() => this.endconfirm(record.planId)}
                  onCancel={this.endcancel}
                  okText="确定"
                  cancelText="取消"
                  placement="topRight"
                >
                  <a disabled={!record.auditStatus || !record.dataPrivilege}>
                    下线
                  </a>
                </Popconfirm>
              )}
              <Divider type="vertical" />
              <Popconfirm
                title="你是否要删除此计划?"
                onConfirm={() => this.deleteconfirm(record.planId)}
                onCancel={this.endcancel}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <a
                  disabled={
                    record.auditStatus === 0 ||
                    record.auditStatus === 1 ||
                    !record.dataPrivilege
                  }
                >
                  删除
                </a>
              </Popconfirm>
            </span>
          );
        }
      }
    ];
    const states = { operate: "add" };
    return (
      <div className={styles.root}>
        {this.state.visible ? (
          <PushModal
            visible
            handleOk={this.handleOk}
            handleCancel={this.handleCancel}
            channelList={channelList}
            dispatch={dispatch}
          />
        ) : null}
        <div className={styles.topSearch}>
          <div style={{ display: "flex" }}>
            <Link
              to={`/intellPush/recommendCenter/plan/addPlan?key=${JSON.stringify(
                states
              )}`}
              // onClick={() => this.reque(states)}
            >
              <Button type="primary" style={{ marginBottom: 17 }}>
                新增
              </Button>
            </Link>
            {btnAuthority[0] &&
              btnAuthority[0].name &&
              btnAuthority[0].name.includes("人工推送") && (
                <Button
                  type="primary"
                  style={{ marginBottom: 17, marginLeft: 20 }}
                  onClick={this.pushModal}
                >
                  人工推送
                </Button>
              )}
          </div>
          <div style={{ color: "rgba(0,0,0,0.85)" }}>
            创建时间：
            <RangePicker
              showTime
              style={{ width: 224, marginLeft: 8, marginRight: 24 }}
              onChange={this.dateChange}
            />
            <Search
              placeholder="计划名称、场景名称、管理员姓名"
              // onSearch={value => console.log(value)}
              style={{ width: 272 }}
              onSearch={this.handleSearch}
              allowClear
              onChange={this.clearChange}
            />
          </div>
        </div>
        <Table
          rowKey={record => record.planId}
          columns={columns}
          locale={{ emptyText: "暂无数据！" }}
          size="middle"
          dataSource={planList}
          loading={loading}
          scroll={planList.length===0?{x:false}:{ x: 1000 }}
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum,
            total: totalCount,
            showTotal: total => `共有 ${total} 条`
          }}
        />
      </div>
    );
  }
}

export default PlanManage;
